In [10]:
def gensquares(N):
for i in range(N):
yield i ** 2
In [11]:
for x in gensquares(10):
print x
In [6]:
import random
random.randint(1,10)
Out[6]:
In [7]:
def rand_num(low,high,n):
for i in range(n):
yield random.randint(low, high)
In [9]:
for num in rand_num(1,10,12):
print num
In [17]:
s = 'hello'
s = iter(s)
print next(s)
Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
If the output has the potential of taking up a large amount of memory and you only intend to iterate through it, you would want to use a generator. (Multiple answers are acceptable here!)
In [18]:
my_list = [1,2,3,4,5]
gencomp = (item for item in my_list if item > 3)
for item in gencomp:
print item